﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using WebApplication3.Data;
using WebApplication3.Model;

namespace WebApplication3.Data
{
    [Route("api/[controller]")]
    [ApiController]
    public class CategoriesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CategoriesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Categories
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Category>>> GetCategories()
        {
            return await _context.Categories.ToListAsync();
        }

        // GET: api/Categories/1
        [HttpGet("{id}")]
        public async Task<ActionResult<Category>> GetCategory(int id)
        {
            var category = await _context.Categories.FindAsync(id);
            if (category == null)
            {
                return NotFound();
            }
            return category;
        }

        // GET: api/Categories/1/questions
        [HttpGet("{id}/questions")]
        public async Task<ActionResult<IEnumerable<Question>>> GetQuestionsByCategoryId(int id)
        {
            var questions = await _context.Questions.Where(q => q.CategoryId == id).ToListAsync();
            if (questions == null || !questions.Any())
            {
                return NotFound();
            }
            return questions;
        }
    }
}
